package middleware

import (
	"context"
	"dcim/pkg/generic-go-kit/core"
	"errors"
	"fmt"
	"github.com/go-kit/kit/endpoint"
)

func NewRecover() endpoint.Middleware {
	return func(next endpoint.Endpoint) endpoint.Endpoint {
		return func(ctx context.Context, request interface{}) (response interface{}, err error) {

			defer func() {
				if err := recover(); err != nil {

					if er, ok := err.(error); ok {
						response = core.ErrResp("", er)
					} else {
						fmt.Println(err)
						response = core.ErrResp("", errors.New(fmt.Sprintf("%s", err)))
					}
				}
			}()
			response, err = next(ctx, request)
			return
		}
	}
}
